package org.ifilm.service;

import java.io.FileInputStream;
import java.io.OutputStream;

import org.springframework.stereotype.Service;

/**
 * 
 * @author Mustafa Genc
 *
 */
@Service
public class FileServiceImpl implements FileService {
	private static int BUFFER_SIZE = 1024 * 8;
	
	@Override
	public void deliverFile(String path, OutputStream outputStream) {
		try {
			returnFile(path, outputStream);
			outputStream.flush();
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void returnFile(String filename, OutputStream outputStream) throws Exception {
		FileInputStream inputStream = null;
		inputStream = new FileInputStream(filename);
		
		try {
			byte[] buf = new byte[BUFFER_SIZE];
			int bytesRead;
			while ((bytesRead = inputStream.read(buf)) != -1) {
				outputStream.write(buf, 0, bytesRead);
				outputStream.flush();
			}
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
		}
	}
}